<template>
  <div>
    <div style="margin: 10px 0">
      <el-input v-model="name" placeholder="请输入名称" style="width: 200px" suffix-icon="el-icon-search">
      </el-input>
      <el-input v-model="description" placeholder="请输入描述" style="width: 200px;margin-left: 5px"
                suffix-icon="el-icon-message">
      </el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">搜索</el-button>
      <el-button type="warning" style="margin-left: 5px" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0;">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-plus"></i></el-button>
      <el-popconfirm
          style="margin-left: 10px"
          confirmButtonText="确定"
          cancelButtonText="取消"
          title="确定删除吗？"
          @confirm="handleDeleteAll"
      >
        <el-button type="danger" slot="reference">批量删除
          <i class="el-icon-delete"></i></el-button>
      </el-popconfirm>
    </div>
    <el-table :data="tableData" border stripe header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange"
    >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column type="index">
      </el-table-column>
      <el-table-column prop="name" label="名称">
      </el-table-column>
      <el-table-column prop="description" label="描述">
      </el-table-column>
      <el-table-column prop="flag" label="角色类型">
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="info" @click="selectMenu(scope.row.id)">分配菜单<i class="el-icon-menu"></i>
          </el-button>
          <el-button type="success" @click="handleEdit(scope.$index, scope.row)">编辑<i class="el-icon-edit"></i>
          </el-button>
          <el-popconfirm
              style="margin-left: 10px"
              confirmButtonText="确定"
              cancelButtonText="取消"
              title="确定删除吗？"
              @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button type="danger" slot="reference">删除
              <i class="el-icon-delete"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="角色信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="80px" size="small">
        <el-form-item label="名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色类型">
          <el-input v-model="form.flag" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配菜单" :visible.sync="menuDialogVisible" width="30%">
      <el-tree
          ref="tree"
          :data="menuData"
          node-key="id"
          show-checkbox
          default-expand-all="ture"
          :check-strictly="true"
          :props="defaultProps"
      >
        <!--   :check-strictly="true":设置父子不互相关联    -->
        <!--    自定义 树节点内容    -->
        <span class="custom-tree-node" slot-scope="{ node, data }">
              <span><i :class="data.icon"></i> {{ data.name }}</span>
          </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      tableData: [],
      // 名称
      name: "",
      // 描述
      description: "",
      // 表单数据
      form: {},
      // 当前页码
      pageNum: 1,
      // 每页条数
      pageSize: 10,
      // 总条数
      total: 10,
      // 表格选中数据
      multipleSelection: [],
      // 表单数据,是否展示
      dialogFormVisible: false,
      // 菜单样式
      menuDialogVisible: false,
      // 菜单样式
      headerBg: 'headerBg',
      // 菜单数据
      menuData: [],
      // 设置数据的那个字段做label,children
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 角色id
      roleId: 0
    }
  },
  methods: {
    load() {
      request.get("/role/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
          description: this.description,
        }
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.data;
          this.total = res.data.total;
        }
      })
    },
    reset() {
      this.username = "";
      this.email = "";
      this.address = "";
      this.load();
    },
    // 分页
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },
    // 分页
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    // 编辑
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.form = row;
    },
    // 删除
    handleDelete(index, row) {
      request.delete("/role/" + row.id).then(res => {
        this.load();
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
      })
    },
    // 批量删除
    handleDeleteAll() {
      let ids = [];
      this.multipleSelection.forEach(item => {
        ids.push(item.id);
      })
      request.post("/role/delBatch", ids).then(res => {
        this.load();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      })
    },
    // 控制新增弹窗
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {
        username: "",
        nickname: "",
        email: "",
        phone: "",
        address: ""
      }
    },
    // 保存
    saveUser() {
      request.post("/role/saveOrUpdate", this.form).then(res => {
        if (res.code === 200) {
          this.load();
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
        } else {
          this.$message({
            type: 'error',
            message: '保存成功'
          });
        }
        this.dialogFormVisible = false;
      })
    },
    // 列表多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 渲染菜单项
    selectMenu(roleId) {
      this.menuDialogVisible = true;
      // 获取角色id
      this.roleId = roleId;
      request.post("/menu/getMenuTree").then(res => {
        if (res.code === 200) {
          this.menuData = res.data;
        }
      })
      // 渲染被选中的id
      request.post("/roleMenu/getRoleMenu/" + roleId).then(res => {
        if (res.code === 200) {
          // 设置选中节点
          this.$refs.tree.setCheckedKeys(res.data);
        }
      })
    },
    // 绑定菜单和角色关系
    saveRoleMenu() {
      // 通过组件自带方法来，获取选中的节点，并且只返回id,包括父亲节点
      let halfCheckedKeys = this.$refs.tree.getCheckedKeys()
      console.log(halfCheckedKeys)
      this.request.post("/roleMenu/setRoleMenu/" + this.roleId, halfCheckedKeys).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '分配成功!'
          });
          this.menuDialogVisible = false;
          const user = JSON.parse(localStorage.getItem('user'))
          // 管理员给自己分配页面，需要重新登录
          if ("admin" == user.username) {
            this.$store.commit('logout')
          }
        } else {
          this.$message({
            type: 'error',
            message: '分配失败!'
          });
        }
      })
    }
  },
  mounted() {
    this.load();
  }
}
</script>

<style scoped>
.headerBg {
  background-color: #eeeeee !important;
}
</style>